package com.cykj.faceledtv.ui.base;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cykj.faceledtv.MyApp;
import com.cykj.faceledtv.R;
import com.cykj.faceledtv.di.component.DaggerFragmentComponent;
import com.cykj.faceledtv.di.component.FragmentComponent;
import com.cykj.faceledtv.di.module.FragmentModule;
import com.cykj.faceledtv.utils.ScreenSwitch;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.Unbinder;

/**
 * fragment基类
 *
 * @author jzh
 * @date 2018/12/13 10:03
 */
public abstract class BaseFragment extends Fragment implements MvpView {

    private BaseActivity baseActivity;
    private Unbinder mUnBinder;
    private View view;
    private Activity mActivity;
    private FragmentComponent mFragmentComponent;
    /**
     * 判断是否需要检测权限，防止不停的弹框
     */
    public boolean isNeedCheck = true;
    public static final int PERMISSION_REQUEST_CODE = 3;
    private int sdkInt = 23;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(false);
    }

    /**
     * 获取布局文件
     *
     * @return 布局id
     */
    protected abstract int getLayoutId();

    /**
     * 初始化控件
     *
     * @param view view
     */
    protected abstract void initWidget(View view);


    protected boolean isVisible;

    /**
     * fragment懒加载
     */
    protected abstract void lazyLoad();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof BaseActivity) {
            BaseActivity activity = (BaseActivity) context;
            this.baseActivity = activity;
            activity.onFragmentAttached();
        } else {
            this.mActivity = (Activity) context;
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mFragmentComponent = DaggerFragmentComponent.builder()
                .fragmentModule(new FragmentModule(this))
                .applicationComponent(MyApp.getInstance().getComponent()).build();
        if (getLayoutId() != 0) {
            view = inflater.inflate(getLayoutId(), container, false);
        }
        initWidget(view);
        lazyLoad();
        return view;
    }

    public Activity getmActivity() {
        return baseActivity == null ? mActivity : baseActivity;
    }


    public FragmentComponent getFragmentComponent() {
        return mFragmentComponent;
    }


    /**
     * 在这里实现Fragment数据的懒加载
     *
     * @param isVisibleToUser Fragment UI对用户是否可见
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    protected void onVisible() {
        lazyLoad();
    }

    protected void onInvisible() {
        hideKeyboard();
    }

    /**
     * 检查权限
     *
     * @param permissions permission
     * @since 2.5.0
     */
    public void checkPermissions(String... permissions) {
        try {
            if (Build.VERSION.SDK_INT >= sdkInt
                    && getmActivity().getApplicationInfo().targetSdkVersion >= sdkInt) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                    BaseFragment.this.requestPermissions(array, PERMISSION_REQUEST_CODE);
                } else {
                    checkPermissionSuccess();
                }
            } else {
                checkPermissionSuccess();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public void checkPermissionSuccess() {

    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions permission
     * @return 权限数组
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= sdkInt
                && getmActivity().getApplicationInfo().targetSdkVersion >= sdkInt) {
            try {
                for (String perm : permissions) {
                    if (!hasPermission(perm) || shouldShowRequestPermissionRationale(perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否所有的权限都已经授权
     *
     * @param grantResults results
     * @return true or false
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] paramArrayOfInt) {
        Logger.d("onRequestPermissionsResult requestCode=" + requestCode);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            } else {
                checkPermissionSuccess();
            }
        }
    }

    /**
     * 显示缺少权限提示信息
     *
     * @since 2.5.0
     */
    public void showMissingPermissionDialog() {
        new AlertDialog.Builder(getmActivity())
                .setMessage(R.string.notifyMsg).setTitle(R.string.tips)
                .setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        startAppSettings();
                    }
                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                MyApp.getInstance().exit();
            }
        }).create().show();
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getmActivity().getPackageName()));
        startActivity(intent);
        isNeedCheck = true;
    }

    /**
     * 是否拥有所有需要的权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    public boolean hasAllPermissions(String... permissions) {
        for (String permission : permissions) {
            if (!hasPermission(permission)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 是否拥有单个权限
     *
     * @param permission permission
     * @return true or false
     */
    @TargetApi(Build.VERSION_CODES.M)
    public boolean hasPermission(String permission) {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
                getmActivity().checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }


    @Override
    public void onDetach() {
        if (baseActivity != null) {
            baseActivity = null;
        }
        if (null != mActivity) {
            mActivity = null;
        }
        super.onDetach();
    }


    @Override
    public void hideKeyboard() {
        if (baseActivity != null) {
            baseActivity.hideKeyboard();
        }
    }

    public void setUnBinder(Unbinder unBinder) {
        mUnBinder = unBinder;
    }

    @Override
    public void onDestroy() {
        if (mUnBinder != null) {
            mUnBinder.unbind();
        }
        hideKeyboard();
        super.onDestroy();
    }

    interface Callback {

        /**
         * attach
         */
        void onFragmentAttached();

        /**
         * detach
         *
         * @param tag tag
         */
        void onFragmentDetached(String tag);
    }

    public void goActivityForResult(Class<?> descClass, int requestCode) {
        ScreenSwitch.switchActivity(getmActivity(), descClass, null, requestCode);
    }

    public void goActivityForResult(Class<?> descClass, Bundle bundle, int requestCode) {
        ScreenSwitch.switchActivity(getmActivity(), descClass, bundle, requestCode);
    }

    public void goActivity(Class<?> descClass, Bundle bundle) {
        goActivityForResult(descClass, bundle, 0);
    }

    public void goActivity(Class<?> descClass) {
        goActivity(descClass, null);
    }
}
